from PySide6.QtWidgets import QWidget,QMessageBox
from views.setting.personbase.personbase import Ui_personbase
from settings.publicvar import engine
from sqlalchemy.orm import Session
from views.schoolInfo.model.SchoolInfo import CreateSchoolInfo
from views.setting.personbase.model.personbase import PersonBase

class PersonBaseView(QWidget,Ui_personbase):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.savebtn.clicked.connect(self.personBase)
        self.restbtn.clicked.connect(self.resetpersonbase)
        self.addschoolitem()
        self.load_personbase()

    def personBase(self):
        name = self.name.text().strip()
        IDcard = self.IDcard.text().strip()
        billing =self.billng_clerk.text().strip()
        schoolcm = self.schoolcm.currentText().strip()
        if name == '' or IDcard == '' or billing == '' or schoolcm == '':
            QMessageBox.critical(None, '保存失败', '所有的空为非空，必须填写！')
        else:
            with Session(engine) as session,session.begin():
                school = session.query(CreateSchoolInfo).filter(CreateSchoolInfo.name==schoolcm).first()
                personbase = PersonBase(name=name,IDcard=IDcard,billing_clerk=billing,school_id=school.id)
                session.add(personbase)

    def resetpersonbase(self):
        self.name.setText('')
        self.IDcard.setText('')
        self.billng_clerk.setText('')
        self.schoolcm.setCurrentText('')
        QMessageBox.critical(None,'重置成功！','重置成功，请重新填写，后保存！')

    def addschoolitem(self):
        with Session(engine) as session,session.begin():
            school = session.query(CreateSchoolInfo).all()
            for tem in school:
                self.schoolcm.addItem(tem.name)

    def load_personbase(self):
        with Session(engine) as session,session.begin():
            personbase = session.query(PersonBase).first()
            self.name.setText(personbase.name)
            self.IDcard.setText(personbase.IDcard)
            self.billng_clerk.setText(personbase.billing_clerk)
            # self.schoolcm.setCurrentText(personbase.school_id)
            print(personbase.school_id.name)
